<?php

namespace App\Http\Controllers\Api\V1_0_0;

use App\Http\Controllers\Controller;
use App\Models\CouponModel;
use App\Models\GoodsModel;
use Dingo\Api\Routing\Helpers;
use Illuminate\Http\Request;

class GoodsController extends Controller
{
    use Helpers;

    public function index(Request $request)
    {
        //排序：默认id desc, 上架时间latest、销量sale、价格price
        $sort = $request->post('sort', '');
        $sortType = $request->post('sortType', '');
        //如果是从分类页跳转过来的，会携带category相关字段
        $categoryLevel1 = $request->post('category_level_1', 0);
        $categoryLevel2 = $request->post('category_level_2', 0);
        $categoryLevel3 = $request->post('category_level_3', 0);
        //如果是从优惠券跳转到可用商品列表，会携带 couponId
        $couponId = $request->post('couponId', 0);
        //分页
        $page = $request->post('page', 1);
        //是否有查询
        $search = $request->post('search', '');
        //如果有查询，走ES查询逻辑，否则，数据库中进行搜索
        if ($search) {

        } else {
            $builder = GoodsModel::query()->where('is_audit', 2)->where('is_delete', 0);
            if ($categoryLevel3) {
                $builder->where('category_level_1', $categoryLevel1);
                $builder->where('category_level_2', $categoryLevel2);
                $builder->where('category_level_3', $categoryLevel3);
            }
            if ($couponId) {
                $coupon = CouponModel::find($couponId);
                if ($coupon) {
                    switch ($coupon['coupon_scope']) {
                        case 1://spu
                            $builder->whereIn('id', explode(',', $coupon['scope_value']));
                            break;
                        case 2://category
                            $builder->whereIn('category_level_3', explode(',', $coupon['scope_value']));
                            break;
                        case 3://all
                            break;
                        default:
                            $builder->where('id', 0);
                    }
                }
            }
            if ($sort && $sortType) {
                $map = [
                    'latest' => 'audit_time',
                    'sale' => 'sales_num',
                    'price' => 'sale_price',
                ];
                $builder->orderBy($map[$sort], $sortType);
            } else {
                $builder->orderBy('putaway_id', 'desc');
            }

            $products = $builder->forPage($page)->get();
        }

        return $this->response->array($products->toArray());
    }

    public function detail($id)
    {

    }

    public function recommends(Request $request)
    {

    }
}
